<?php

session_start();

class SettingsTemplate{

 public static function showPricePanel(){
   //metodos de negocio
   global $wpdb;
    
    if (isset($_POST['export_year'])) {
       $year_selected = $_POST['export_year'];
    }

   if( isset($_POST) && isset($_POST['m3_consumo']) && $_POST['cambia_precio']==0){
        //data
        $data_year_m3 = $_POST['year_m3'];
        $data_year_kw = $_POST['year_kw'];
        $current_year = date('Y');
        $data_month_m3 = $_POST['month_m3'];
        $data_month_kw = $_POST['month_kw'];
        $current_month = date('n');
        $consumo_tipo_m3 =  $_POST['m3_consumo'];
        $consumo_tipo_kw =  $_POST['kw_consumo'];
        $precio_tipo_m3 =  $_POST['m3_precio'];
        $precio_tipo_kw =  $_POST['kw_precio'];
        
        if($_POST['tipo_submit']=="m3"){
            for($y = $data_year_m3; $y <= $current_year; $y++){
                $begin_month = $y == $data_year_m3 ? $data_month_m3 : 1;
                $end_month = $y < $current_year ? 12 : $current_month;
                //para m3
                for($m = $begin_month; $m <= $end_month; $m++){
                    $wpdb->query('UPDATE 
                                    `bpa_registry_baseline` 
                                SET 
                                    `base` = '. $consumo_tipo_m3 .'
                                WHERE 
                                    `type_id` = 1 AND 
                                    `year` = '. $y .' AND 
                                    `month` = '. $m);
                }
            } 
        }else if($_POST['tipo_submit']=="kw"){
            for($y = $data_year_kw; $y <= $current_year; $y++){
                $begin_month = $y == $data_year_kw ? $data_month_kw : 1;
                $end_month = $y < $current_year ? 12 : $current_month;
                //para kw
                for($m = $begin_month; $m <= $end_month; $m++){
                    $wpdb->query('UPDATE 
                                    `bpa_registry_baseline` 
                                SET 
                                    `base` = '. $consumo_tipo_kw .'
                                WHERE 
                                    `type_id` = 2 AND 
                                    `year` = '. $y .' AND 
                                    `month` = '. $m);
                }
            } 
        }else if($_POST['tipo_submit']=="precio_m3"){  
            $wpdb->query('UPDATE 
                            `bpa_consumption_type` 
                        SET 
                            `price` = '. $precio_tipo_m3 .'
                        WHERE 
                            `id` = 1');      
            
        } 
        else if($_POST['tipo_submit']=="precio_kw"){  
            $wpdb->query('UPDATE 
                            `bpa_consumption_type` 
                        SET 
                            `price` = '. $precio_tipo_kw .'
                        WHERE 
                            `id` = 2');      
            
        }
        else if(is_null($year_selected ) or !is_null($year_selected)){
            echo "";
        }
        ?>
        <div id='notice' class='updated fade'><p>Valores actualizados correctamente.</p></div>
        <?php
    }
?>

<?php 
//metodos de negocio
global $wpdb;
//obtenemos el ultimo anio y mes registrado para cada tipo
$last_base_year_month_m3 = $wpdb->get_results('SELECT 
                                                id,
                                                year,
                                                month,
                                                type_id,
                                                base
                                            FROM 
                                                bpa_registry_baseline 
                                            WHERE
                                                type_id = 1
                                            ORDER BY id DESC LIMIT 1' 
                            , ARRAY_A);
$last_base_year_month_kw = $wpdb->get_results('SELECT 
                                                id,
                                                year,
                                                month,
                                                type_id,
                                                base
                                            FROM 
                                                bpa_registry_baseline 
                                            WHERE
                                                type_id = 2
                                            ORDER BY id DESC LIMIT 1' 
                            , ARRAY_A);
//obtenemos el anio y mes del servidor:
$year = date('Y');
$month = date('n');
//si los datos no son actuales, el sistema inserta los faltantes hasta la fecha
if( !($last_base_year_month_m3[0]['year']==$year && $last_base_year_month_m3[0]['month']==$month) ){
    //data
    $last_data_year = $last_base_year_month_m3[0]['year'];
    $current_year = $year;
    $last_data_month = $last_base_year_month_m3[0]['month'];
    $current_month = $month;
    $precio_base_tipo_m3 = $last_base_year_month_m3[0]['base'];
    $precio_base_tipo_kw = $last_base_year_month_kw[0]['base'];
    $tipo_m3 = 1;
    $tipo_kw = 2;
    
    for($y = $last_data_year; $y <= $current_year; $y++){
        $begin_month = $y == $last_data_year ? $last_data_month + 1 : 1;
        $end_month = $y < $current_year ? 12 : $current_month;
        //para m3
        for($m = $begin_month; $m <= $end_month; $m++){
            $wpdb->query($wpdb->prepare("INSERT INTO 
                                            bpa_registry_baseline (type_id, year, month, base) 
                                        VALUES (%d, %d, %d, %f)", $tipo_m3, $y, $m, $precio_base_tipo_m3));
        }
        //para kw
        for($m = $begin_month; $m <= $end_month; $m++){
            $wpdb->query($wpdb->prepare("INSERT INTO 
                                            bpa_registry_baseline (type_id, year, month, base) 
                                        VALUES (%d, %d, %d, %f)", $tipo_kw, $y, $m, $precio_base_tipo_kw));
        }
    }   
}
//obtenemos los anios 
$base_year_list = $wpdb->get_results('SELECT DISTINCT year 
                                FROM 
                                      bpa_registry_baseline
                                ORDER BY 
                                    year ASC' 
                            , ARRAY_A);

//obtenemos los precio actual del agua ID = 1
$precio_m3 = $wpdb->get_row('SELECT price 
                                FROM 
                                      bpa_consumption_type
                                WHERE 
                                    id = 1');
//obtenemos los precio actual de la electricidad ID = 2
$precio_kw = $wpdb->get_row('SELECT price 
                                FROM 
                                      bpa_consumption_type
                                WHERE 
                                    id = 2');

//obtenemos los meses
$base_month_list = array();
   $base_month_list[1] = "Enero";
   $base_month_list[2] = "Febrero";
   $base_month_list[3] = "Marzo";
   $base_month_list[4] = "Abril";
   $base_month_list[5] = "Mayo";
   $base_month_list[6] = "Junio";
   $base_month_list[7] = "Julio";
   $base_month_list[8] = "Agosto";
   $base_month_list[9] = "Septiembre";
   $base_month_list[10] = "Octubre";
   $base_month_list[11] = "Noviembre";
   $base_month_list[12] = "Diciembre";
   
//se establece los datos a mostrar
$anio_mostrar_m3 = $last_base_year_month_m3[0]['year'];
$mes_mostrar_m3  = $last_base_year_month_m3[0]['month'];
$base_mostrar_m3 = $last_base_year_month_m3[0]['base'];
if($_POST['cambia_precio']==1){
    $find_base_year_month_m3 = $wpdb->get_results('SELECT 
                                                id,
                                                year,
                                                month,
                                                type_id,
                                                base
                                            FROM 
                                                bpa_registry_baseline 
                                            WHERE
                                                type_id = 1
                                                and year = '.$_POST['year_m3'].'
                                                and month = '.$_POST['month_m3'].'
                                            ORDER BY id DESC LIMIT 1' 
                            , ARRAY_A);
    if(count($find_base_year_month_m3)>0){
        $anio_mostrar_m3 = $find_base_year_month_m3[0]['year'];
        $mes_mostrar_m3  = $find_base_year_month_m3[0]['month'];
        $base_mostrar_m3 = $find_base_year_month_m3[0]['base'];
    }else{
      echo "<div id='notice_error' class='error fade'><p>Valores no encontrados.</p></div>";  
    }    
}
$anio_mostrar_kw = $last_base_year_month_kw[0]['year'];
$mes_mostrar_kw  = $last_base_year_month_kw[0]['month'];
$base_mostrar_kw = $last_base_year_month_kw[0]['base'];
if($_POST['cambia_precio']==2){
    $find_base_year_month_kw = $wpdb->get_results('SELECT 
                                                id,
                                                year,
                                                month,
                                                type_id,
                                                base
                                            FROM 
                                                bpa_registry_baseline 
                                            WHERE
                                                type_id = 2
                                                and year = '.$_POST['year_kw'].'
                                                and month = '.$_POST['month_kw'].'
                                            ORDER BY id DESC LIMIT 1' 
                            , ARRAY_A);
    if(count($find_base_year_month_kw)>0){
        $anio_mostrar_kw = $find_base_year_month_kw[0]['year'];
        $mes_mostrar_kw  = $find_base_year_month_kw[0]['month'];
        $base_mostrar_kw = $find_base_year_month_kw[0]['base'];
    }else{
      echo "<div id='notice_error' class='error fade'><p>Valores no encontrados.</p></div>";  
    }    
}
?>    
     
<h1>Gesti&oacute;n de Par&aacute;metros del Sistema</h1>

<script type="text/javascript">
    
jQuery(document).ready(function($){
        $('.param_decimal').keyup(function(){
            var val = $(this).val();
            if(isNaN(val)){
                val = val.replace(/[^0-9\.]/g,'');
                if(val.split('.').length>2) 
                    val =val.replace(/\.+$/,"");
            }
            $(this).val(val); 
        });
});
    
    function envia_select(tipo) {
        var cambia_precio = document.getElementById("cambia_precio");
        cambia_precio.setAttribute("value", tipo);
        document.getElementById("form_consumo").submit();
    } 

    function envia_submit(tipo) {
        var tipo_submit = document.getElementById("tipo_submit");
        tipo_submit.setAttribute("value", tipo);
        document.getElementById("form_consumo").submit();
    }

    function envia_año(){
        document.getElementById("form_consumo").submit();
    }     
</script>

<form id="form_consumo" action="" method="POST">    

    <input id="cambia_precio" name="cambia_precio" type="hidden" value="0"/>
    <input id="tipo_submit" name="tipo_submit" type="hidden" value=""/>
    <style>
        .label_consumo{
            width: 70px;
            display: inline-block;
        }
        .label_precio{
            width: 240px;
            display: inline-block;
        }
        .param_colum{
            width: 400px;
            float:left;
            margin-right:20px;
            position:relative;
        }
        .param_text{
            width: 100px;
        }
        .param_separador{
            clear: both;
            margin-top: 20px;
            margin-bottom: 20px;
        }
        .param_subtitulo{
            margin-top: 30px;
        }
    </style>  
    
    <h3 class="param_subtitulo">1. Consumo per c&aacute;pita ideal (usado para L&iacute;nea Base)</h3>
    <div class="param_colum param_izq">
        <p>Consumo per c&aacute;pita ideal mensual en <b>agua</b> (m<sup>3</sup>)</p>
        <div>
            <div class="select-input year-input">
                <label class="label_consumo" for="year_m3">A&ntilde;o: </label>
                <select id="year_m3" name="year_m3" onchange="envia_select(1)">
                    <?php foreach($base_year_list as $year) { ?>
                        <option value="<?php echo $year['year']; ?>" <?php if($year['year']==$anio_mostrar_m3) echo " selected=true"; ?>  ><?php echo $year['year']; ?></option>
                    <?php } ?>
                </select>
            </div>
            <div class="select-input month-input">
                <label class="label_consumo" for="month_m3">Mes: </label>
                <select id="month_m3" name="month_m3"  onchange="envia_select(1)">
                    <?php 
                        $index = 0;
                        foreach($base_month_list as $month) { 
                            $index++;
                    ?>
                        <option value="<?php echo $index; ?>" <?php if($index==$mes_mostrar_m3) echo " selected=true"; ?> ><?php echo $month; ?></option>
                    <?php } ?>
                </select>
            </div>
            <div class="input month-input">
                <label class="label_consumo"for="m3_consumo">Consumo: </label>
                <input type="text" name="m3_consumo" value="<?php echo $base_mostrar_m3; ?>" class="param_text param_decimal" />
            </div>
        </div>

        <p class="submit">
            <input type="button" name="submit_m3" class="button-primary" value="Actualizar consumos de agua" onclick="envia_submit('m3')"/>
            <p><i>Los consumos se actualizar&aacute;n a partir del periodo seleccionado</i></p>
        </p>
    </div>
    <div class="param_colum param_der">
        <p>Consumo per c&aacute;pita ideal mensual en <b>electricidad</b> (KiloWatts)</p>
        <div>
            <div class="select-input year-input">
                <label class="label_consumo" for="year_kw">A&ntilde;o: </label>
                <select id="year_kw" name="year_kw" onchange="envia_select(2)">
                    <?php foreach($base_year_list as $year) { ?>
                        <option value="<?php echo $year['year']; ?>" <?php if($year['year']==$anio_mostrar_kw) echo " selected=true"; ?>  ><?php echo $year['year']; ?></option>
                    <?php } ?>
                </select>
            </div>
            <div class="select-input month-input">
                <label class="label_consumo" for="month_kw">Mes: </label>
                <select id="month_kw" name="month_kw"  onchange="envia_select(2)">
                    <?php 
                        $index = 0;
                        foreach($base_month_list as $month) { 
                            $index++;
                    ?>
                        <option value="<?php echo $index; ?>" <?php if($index==$mes_mostrar_kw) echo " selected=true"; ?> ><?php echo $month; ?></option>
                    <?php } ?>
                </select>
            </div>
            <div class="input month-input">
                <label class="label_consumo"for="kw_consumo">Consumo: </label>
                <input type="text" name="kw_consumo" value="<?php echo $base_mostrar_kw; ?>" class="param_text param_decimal" />
            </div>
        </div>

        <p class="submit">
            <input type="button" name="submit_kw" class="button-primary" value="Actualizar consumos de electricidad" onclick="envia_submit('kw')"/>
            <p><i>Los consumos se actualizar&aacute;n a partir del periodo seleccionado</i></p>
        </p>
    </div>
    <hr class="param_separador">
    
    <!-- Precio -->
    <h3 class="param_subtitulo">2. Precio por tipo de consumo (usado para c&aacute;lculo de ahorro)</h3>
    <div class="param_colum param_izq">
        <div>
            <div class="input month-input">
                <label class="label_precio"for="m3_precio">Precio promedio actual por metro c&uacute;bico</label>
                <input type="text" name="m3_precio" value="<?php echo $precio_m3->price; ?>" class="param_text param_decimal" />
            </div>
        </div>

        <p class="submit">
            <input type="button" name="submit_precio_m3" class="button-primary" value="Actualizar precio de agua" onclick="envia_submit('precio_m3')"/>
        </p>
    </div>
    <div class="param_colum param_der">
        <div>
            <div class="input month-input">
                <label class="label_precio"for="kw_precio">Precio promedio actual por kilowatt/hora</label>
                <input type="text" name="kw_precio" value="<?php echo $precio_kw->price; ?>" class="param_text param_decimal" />
            </div>
        </div>

        <p class="submit">
            <input type="button" name="submit_precio_kw" class="button-primary" value="Actualizar precio de electricidad" onclick="envia_submit('precio_kw')"/>
        </p>
    </div>
    <hr class="param_separador">
        <h3>3. Exportación de datos de las PYME'S</h3>
        <div class="param_colum param_izq">
            <div>
                <div class="select-input year-input">
                    <label class="label_consumo" for="year">A&ntilde;o: </label>
                    <select id="year" name="export_year" onchange="envia_año();">
                        <?php foreach($base_year_list as $year) { ?>
                        <option value="<?php echo $year['year']; ?>" <?php if($year['year']==$year_selected) echo " selected=true"; ?>  ><?php echo $year['year']; ?></option>
                        <?php } ?>
                        <?php
                        $_SESSION['year'] = $year_selected;
                        ?>
                    </select>
                    <p class="submit" >
                        <a href="<?php echo get_template_directory_uri();?>/export-excel/generator-admin.php">
                            <input type="button" id="export" class="button-primary" value="Exportar" />
                        </a>
                     </p>
                </div>  
            </div>
        </div>
</form>
<?php

} 
}
